/*
 * Copyright (c) 2011. This file is public under GPLv3 license.
 * For more information about license please refer to http://www.gnu.org/licenses/gpl.html
 */

package com.freetools.watchdog.commands;

import com.freetools.watchdog.engine.LogParser;
import com.freetools.watchdog.exceptions.CommandErrorException;
import com.freetools.watchdog.model.CommandName;
import com.freetools.watchdog.model.IModelHolder;
import com.freetools.watchdog.model.IRecord;
import org.apache.log4j.Logger;

import java.io.IOException;

/**
 * @author Michael Morozov
 */
@CommandName("run")
public class RunCmd extends Command
{
    private static final Logger log = Logger.getLogger(RunCmd.class);
    public static final int FLUSH_RECORDS_COUNT = 10;

    public void execute(IModelHolder model) throws CommandErrorException
    {
        LogParser.perform(model);
        try
        {
            int flushCounter = FLUSH_RECORDS_COUNT;
            for (IRecord record : model.getRecords())
            {
                model.getSpool().write(model.getRecordFormatter().format(model, record));
                if (flushCounter < 0)
                {
                    model.getSpool().flush();
                    flushCounter = FLUSH_RECORDS_COUNT;
                }
                flushCounter--;
            }
            model.getSpool().flush();

        } catch (IOException e)
        {
            log.error("Cannot write to the spool because exception", e);
        }
    }
}
